<template>
  <el-dialog v-el-drag-dialog width="800px" :title="formName" :visible="show" @update:visible="updateShow">
    <pop-stepper :tips="tips" :acttips="actTips" @choseTips="
        (name) => {
          actTips = name;
        }
      ">
      <el-form ref="dataForm" :rules="rules" :model="form" label-position="right" label-width="115px" v-show="actTips == '基础信息'">
        <el-form-item label="登录账号：" prop="LoginName">
          <el-input :disabled="loginName" v-model="form.LoginName" style="width: 500px" placeholder="登录系统所用" />
        </el-form-item>
        <el-form-item label="登录密码：" prop="LoginPwd">
          <el-input v-model="form.LoginPwd" type="password" placeholder="登录系统所用" style="width: 500px" />
        </el-form-item>
        <el-form-item label="用户名：" prop="UserName">
          <el-input v-model="form.UserName" style="width: 500px" placeholder="系统中显示的用户名称" />
        </el-form-item>
        <el-form-item label="联系电话：" prop="UserPhone">
          <el-input v-model="form.UserPhone" style="width: 500px" />
        </el-form-item>
        <el-form-item label="联系地址：" prop="UserAddr">
          <el-input v-model="form.UserAddr" style="width: 500px" />
        </el-form-item>
        <el-form-item label="用户头像：" prop="SignIcon">
          <div class="flex">
            <el-input v-model="form.SignIcon" style="width: 360px" disabled />

            <el-popover placement="bottom" style="width: 100px" trigger="click">
              <div class="m-b-1">
                <div v-for="item of user_icon_m" :key="item.icon" class="userAvater" :class="item.icon" @click="form.SignIcon = item.icon"></div>
              </div>
              <div>
                <div v-for="item of user_icon_f" :key="item.icon" class="userAvater" :class="item.icon" @click="form.SignIcon = item.icon"></div>
              </div>
              <el-button slot="reference">选择</el-button>
            </el-popover>
            <div :class="form.SignIcon" style="width: 40px"></div>
          </div>
        </el-form-item>
        <!--<el-form-item label="邮箱地址" prop="UserEmail">
          <el-input v-model="form.UserEmail" style="width: 500px;" />
        </el-form-item>
        <el-form-item label="备注" prop="Remark">
          <el-input v-model="form.Remark" style="width: 500px;" />
        </el-form-item>-->
        <el-form-item label="所属上级：" prop="UserParent">
          <el-select v-model="form.UserParent" filterable placeholder="请选择" style="width: 500px">
            <el-option v-for="item in userList" :key="item.UserName" :label="item.UserPhone ? (item.UserName + '    ' + item.UserPhone) : item.UserName" :value="item.Id" style="width: 500px">
              <span style="float: left">{{ item.UserName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.UserPhone }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="公司名称：" prop="OrgId">
          <el-select v-model="form.OrgId" filterable placeholder="请选择" style="width: 500px">
            <el-option v-for="item in orgList" :key="item.Id" :label="item.OrgName" :value="item.Id" style="width: 500px">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="身份角色：" prop="RoleId">
          <el-select v-model="form.RoleId" filterable placeholder="请选择" :disabled="loginName" style="width: 500px">
            <el-option v-for="item in userRoleList" :key="item.Id" :label="item.RoleName" :value="item.Id" style="width: 500px">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开户信息：">
          <el-form :inline="true">
            <el-form-item prop="IsSkipBank">
              <el-checkbox v-model="form.IsSkipBank"></el-checkbox>
            </el-form-item>
            <el-form-item label="钱包提现开关：" prop="Withdrawal" class="m-l-2">
              <el-switch v-model="form.Withdrawal">
              </el-switch>
            </el-form-item>
          </el-form>

        </el-form-item>

      </el-form>
      <el-form ref="dataForm2" :model="form.Bank" :rules="rules2" label-position="right" label-width="100px" v-show="actTips == '开户信息'">
        <el-form-item label="户名：" prop="AccountName">
          <el-input v-model="form.Bank.AccountName" style="width: 500px" />
        </el-form-item>
        <el-form-item label="卡号：" prop="CardNum">
          <el-input v-model="form.Bank.CardNum" @change="getBankName()" style="width: 500px" />
        </el-form-item>
        <el-form-item label="开户行：" prop="BankName">
          <el-input v-model="BankName" disabled style="width: 500px" />
        </el-form-item>
      </el-form>
    </pop-stepper>
    <div slot="footer" class="dialog-footer">
      <el-button @click="updateShow(false)"> 取消 </el-button>
      <el-button type="primary" @click="save">
        {{ actTips == "基础信息" && form.IsSkipBank?  "下一步" : "保存"  }}</el-button>
    </div>
  </el-dialog>
</template>
<script>
  import { deepClone } from '@/utils'
  import { saveUser, getUser, GetById } from '@/api/system/user'
  import { getUserRole } from '@/api/system/user-role'
  import { getList } from '@/api/organization'
  import { mapState } from 'vuex'
  import popStepper from '@/components/popupStepper'
  import { verifyBankCard } from '@/api/system/withdraw'
  export default {
    components: { popStepper },
    props: {
      isuser: {
        type: Boolean,
        default: false
      },
      show: {
        type: Boolean,
        default() {
          return false
        }
      },
      formData: {
        type: Object,
        default() {
          return {}
        }
      }
    },
    data() {
      return {
        BankName: null,
        loginName: false,
        userList: [],
        userRoleList: [],
        orgList: [],
        actTips: '基础信息',

        form: {
          SignIcon: '',
          Bank: {
            BankName: null,
            AccountName: '',
            CardNum: '',

          }

        },
        formTmpl: {
          Bank: {
            Id: "00000000-0000-0000-0000-000000000000"
          },
          SignIcon: '',
          Withdrawal: true

        },
        rules: {
          LoginName: [
            { required: true, message: '登录名称必填', trigger: 'blur' },
            { min: 1, max: 50, message: '登录名称长度在 1 到 50 个字符', trigger: 'blur' }
          ],
          SignIcon: [{ required: true, message: '头像必选', trigger: 'blur' }],
          LoginPwd: [{ required: true, message: '必填', trigger: 'blur' }],
          UserName: [{ required: true, message: '必填', trigger: 'blur' }],
          UserPhone: [{ required: true, message: '必填', trigger: 'blur' }],
          OrgId: [{ required: true, message: '必填', trigger: 'blur' }],
          RoleId: [{ required: true, message: '必填', trigger: 'blur' }],
        },
        rules2: {
          AccountName: [{ required: true, message: '必填', trigger: 'blur' }],
          CardNum: [{ required: true, message: '必填', trigger: 'blur' }],
          BankName: [{ required: true, message: '必填', trigger: 'blur' }],
        },
        user_icon_m: [
          { icon: "user_m_1" },
          { icon: "user_m_2" },
          { icon: "user_m_3" },
          { icon: "user_m_4" },
          { icon: "user_m_5" },
          { icon: "user_m_6" },
        ],
        user_icon_f: [
          { icon: "user_f_1" },
          { icon: "user_f_2" },
          { icon: "user_f_3" },
          { icon: "user_f_4" },
          { icon: "user_f_5" },
          { icon: "user_f_6" },
        ],
      }
    },
    computed: {
      tips() {
        if (!this.form.IsSkipBank) {
          return [
            {
              name: '基础信息',
              active: false,
              icon: 'el-icon-user'
            }
          ]
        } else {
          return [
            {
              name: '基础信息',
              active: false,
              icon: 'el-icon-user'
            },
            {
              name: "开户信息",
              active: false,
              icon: 'el-icon-coin'
            }
          ]
        }
      },
      formName() {
        const id = this.form.Id

        if (id) {
          this.loginName = true
          this.BankName = this.form.Bank.BankName
          this.userList.forEach((value, index, array) => {
            if (value.Id == id) {
              array.splice(index, 1)
            }
          })

          return '编辑'
        }
        if (this.isuser) {
          this.formTmpl.Withdrawal = true
        } else {
          this.formTmpl.Withdrawal = false
        }
        this.loginName = false

        return '新增'
      },
      ...mapState({
        userId: state => state.user.id,
      }),
    },
    watch: {
      formData: {
        deep: true,
        immediate: true,
        handler(val) {
          if (this.$refs['dataForm']) {
            this.$refs['dataForm'].clearValidate()
          }
          if (val.Id && val.Id != '00000000-0000-0000-0000-000000000000') {
            // console.log('这是编辑')
            this.GetByIdFun(val.Id)
          } else {
            this.form = deepClone({ ...this.formTmpl, ...val })
          }
          if (this.formName == '新增' || this.formName == '编辑') {

            this.getlistfun()
          }

        }
      }
    },
    create() {
    },
    methods: {
      getlistfun() {
        if (this.show) {
          console.log('打开')
          this.getUserList()
          this.getUserRoleList()
          this.getOrgList()
        }
      },
      async getUserList() {
        const data = { IsSystemUser: !this.isuser, IsPaging: false }
        const { Data } = await getUser(data)
        Data.unshift({ UserName: '无上级', Id: "00000000-0000-0000-0000-000000000000" })

        this.userList = Data || []
        console.log(this.userList)
      },
      async getUserRoleList() {
        const data = {
          IsPaging: false,
          FilterRole: this.isuser
        }
        const { Data } = await getUserRole(data)
        this.userRoleList = Data || []
      },
      async getOrgList() {
        const { Data } = await getList({ IsPaging: false })
        this.orgList = Data || []
      },
      updateShow(val) {
        this.$emit('update:show', val)
      },
      afterSave() {
        this.$notify({
          title: '操作成功',
          message: 'success',
          type: 'success',
          duration: 2000
        })
        this.updateShow(false)
        this.$emit('finish')
      },
      GetByIdFun(id) {
        GetById({ Id: id }).then(res => {
          // console.log(res)
          if (!res.Data.Bank) {
            res.Data.Bank = {}
          }
          // let form = this.$deepClone(res.Data)
          // form.SignIcon
          this.form = this.$deepClone(res.Data)

        })
      },
      save() {
        this.$refs['dataForm'].validate((valid) => {
          let formData = deepClone(this.form)
          if (valid) {
            if (!formData.IsSkipBank) {
              // 非本人修改的话 不用填开户信息
              formData.IsSkipBank = true  //与后台逻辑相反 所以需要取反 直接跳过验证
              saveUser(formData).then(() => {
                this.afterSave()
              })
              return
            } else if (this.actTips == '基础信息') {
              this.actTips = '开户信息'
              return
            }
            if (this.actTips == '开户信息' && formData.IsSkipBank) { //如果是本人修改 则需要填写开户行信息等
              formData.IsSkipBank = !formData.IsSkipBank  //与后台逻辑相反 所以需要取反 
              this.$refs['dataForm2'].validate(res => {
                if (res) {
                  saveUser(formData).then(() => {
                    this.afterSave()
                  })
                }
              })
            }
          }
        })

      },
      getBankName() {
        this.BankName = null
        this.form.Bank.BankName = null
        verifyBankCard({ "CardNum": this.form.Bank.CardNum }).then(res => {
          this.BankName = res.Data.BankName
          this.form.Bank.BankName = this.BankName

        }).catch(err => { })
      },


      async valid(id) {
        const { code } = await toggleValidShare({
          Id: id
        })
        if (code == 200) {
          this.$notify({
            title: '切换成功',
            message: 'success',
            type: 'success',
            duration: 2000
          })
        }
      },
    }
  }
</script>
<style scoped>
  .userAvater {
    cursor: pointer;
    width: 40px;
    height: 40px;
    border-radius: 10px;
    overflow: hidden;
    display: inline-block;
    margin-right: 10px;
  }
  .userAvater:hover {
    background-color: #d8e5f5;
  }
</style>